package net.hn.hnms.biz.performance.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import net.hn.hnms.biz.performance.domain.PerformanceScoring;
import net.hn.hnms.biz.performance.domain.PerformanceScoringDetails;
import net.hn.hnms.biz.performance.domain.PerformanceTemplate;
import net.hn.hnms.biz.performance.domain.SafetyHazard;
import net.hn.hnms.biz.performance.mapper.PerformanceScoringDetailsMapper;
import net.hn.hnms.biz.performance.mapper.PerformanceScoringMapper;
import net.hn.hnms.biz.performance.mapper.PerformanceTemplateMapper;
import net.hn.hnms.biz.performance.mapper.SafetyHazardMapper;
import net.hn.hnms.biz.performance.request.PerformanceScoringAndDetailsReq;
import net.hn.hnms.biz.performance.request.PerformanceScoringReq;
import net.hn.hnms.biz.performance.request.SafetyHazardReq;
import net.hn.hnms.biz.performance.service.PerformanceScoringService;
import net.hn.hnms.biz.performance.vo.PerformanceScoringVo;
import net.hn.hnms.biz.performance.vo.SafetyHazardVo;
import net.hn.hnms.sys.common.core.utils.BeanCopyUtils;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class PerformanceScoringServiceImpl implements PerformanceScoringService {

    @Autowired
    private PerformanceScoringMapper performanceScoringMapper;
    @Autowired
    private PerformanceScoringDetailsMapper performanceScoringDetailsMapper;

    @Autowired
    private PerformanceTemplateMapper performanceTemplateMapper;

    @Autowired
    private SafetyHazardMapper safetyHazardMapper;

    @Override
    public Page<List<PerformanceScoringVo>> getPerformanceScoringByNameAndScoringTypeAndScoringDateAndScoringTemplateId(PageQuery pageQuery, PerformanceScoringReq req) {
        Page<List<PerformanceScoringVo>> list = performanceScoringMapper.getPerformanceScoringByNameAndScoringTypeAndScoringDateAndScoringTemplateId(pageQuery.build(), req);

//        for (int i = 0; i < s.size(); i++) {
//            String jsonString=s.get(i).getPerformanceScoringDetails();
//            Map<String, Object> map = JSON.parseObject(jsonString, new TypeReference<Map<String, Object>>() {});
//            System.err.println(map);
//        }
//        ResponsePage<PerformanceScoringVo> ss=null;
//        BeanCopyUtils.copy(s, ss);
        return list;
    }

    @Override
    public int deleteById(List<String> ids) {

        int i1 = performanceScoringDetailsMapper.deletePerformanceScoringByParentId(ids);
        int i2 = performanceScoringMapper.deletePerformanceScoringByIds(ids);
        return i1 + i2;
    }

    @Override
    public int update(PerformanceScoringReq req) {
        PerformanceScoring performanceScoring = new PerformanceScoring();
        BeanCopyUtils.copy(req, performanceScoring);
        return performanceScoringMapper.updateById(performanceScoring);
    }

    @Override
    public int save(PerformanceScoringAndDetailsReq req) {

        PerformanceScoring performanceScoring = new PerformanceScoring();

        BeanCopyUtils.copy(req, performanceScoring);

        LambdaQueryWrapper<PerformanceScoring> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StrUtil.isNotBlank(req.getScoringDate()), PerformanceScoring::getScoringDate, req.getScoringDate());
        lqw.eq(StrUtil.isNotBlank(req.getScoringType()), PerformanceScoring::getScoringType, req.getScoringType());
        lqw.eq(StrUtil.isNotBlank(req.getPerformanceTemplateId()), PerformanceScoring::getPerformanceTemplateId, req.getPerformanceTemplateId());

        List<PerformanceScoring> performanceScoringList = performanceScoringMapper.selectList(lqw);
        PerformanceTemplate performanceTemplate = performanceTemplateMapper.selectById(Integer.parseInt(req.getPerformanceTemplateId()));
        performanceScoring.setPerformanceTemplateName(performanceTemplate.getPerformanceTemplateName());
        if (performanceScoringList == null || performanceScoringList.size() == 0) {
            performanceScoringMapper.insert(performanceScoring);
            log.info(performanceScoring.toString());
        } else {
            performanceScoring.setPerformanceScoringId(performanceScoringList.get(0).getPerformanceScoringId());
        }


        req.getScoreItems().forEach(s -> {
            PerformanceScoringDetails performanceScoringDetails = new PerformanceScoringDetails();
            BeanCopyUtils.copy(req, performanceScoringDetails);

            performanceScoringDetails.setPerformanceScoringId(performanceScoring.getPerformanceScoringId());
            performanceScoringDetails.setScoringType(req.getScoringType());
            performanceScoringDetails.setScoringDate(req.getScoringDate());
            performanceScoringDetails.setUserName(s.get("userName"));
            performanceScoringDetails.setName(s.get("name"));
            performanceScoringDetails.setTotalPoints(Double.parseDouble(s.get("totalPoints")));
            s.remove("userName");
//            s.remove("name");
            performanceScoringDetails.setScoreItems(JSON.toJSONString(s));

            performanceScoringDetailsMapper.insert(performanceScoringDetails);

        });


        return 0;
    }

    @Override
    public List<SafetyHazardVo> getSafetyHazard(SafetyHazardReq req) {
        req.setAssessmentDate(req.getAssessmentDate() + "-01");
        if (req.getType().equals("1")) {
            //月度
            String assessmentDate = req.getAssessmentDate(); // 获取考核日期字符串
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate date = LocalDate.parse(assessmentDate, formatter); // 解析成LocalDate对象

            // 获取月初日期
            LocalDate startOfMonth = date.with(TemporalAdjusters.firstDayOfMonth());
            // 获取月末日期
            LocalDate endOfMonth = date.with(TemporalAdjusters.lastDayOfMonth());

            // 转换成字符串格式
            String startOfMonthStr = startOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String endOfMonthStr = endOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

            req.setStartDate(startOfMonthStr);
            req.setEndDate(endOfMonthStr);
        } else {
            //季度
            // 获取年度和季度
            int assessmentScopeYear = Integer.parseInt(req.getAssessmentScopeYear());
            int assessmentScopeQuarter = Integer.parseInt(req.getAssessmentScopeQuarter());

            // 计算季度的第一个月和最后一个月
            int firstMonthOfQuarter = (assessmentScopeQuarter - 1) * 3 + 1;
            int lastMonthOfQuarter = assessmentScopeQuarter * 3;

            // 获取季度的开始和结束日期
            LocalDate startOfQuarter = LocalDate.of(assessmentScopeYear, firstMonthOfQuarter, 1);
            LocalDate endOfQuarter = LocalDate.of(assessmentScopeYear, lastMonthOfQuarter, 1).with(TemporalAdjusters.lastDayOfMonth());

            // 转换成字符串格式
            String startOfQuarterStr = startOfQuarter.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String endOfQuarterStr = endOfQuarter.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

            // 设置到req对象中
            req.setStartDate(startOfQuarterStr);
            req.setEndDate(endOfQuarterStr);
        }
        List<SafetyHazardVo> list = new ArrayList<>();
        String[] names = req.getNames().split(",");
        DynamicDataSourceContextHolder.push("swyt");
        SafetyHazard safetyHazard = null;
        for (String name : names) {
            safetyHazard = safetyHazardMapper.getSafetyHazard(req, name);
            safetyHazard.setName(name);
            list.add(BeanCopyUtils.copy(safetyHazard, SafetyHazardVo.class));
        }
        DynamicDataSourceContextHolder.clear();

        return list;
    }

}
